<template>
  <div class="page">
    <div class="notice">
      <van-notice-bar left-icon="volume-o" text="请认真填写居民信息采集表( * 为必填项)" />
    </div>

    <div class="form">
      <van-form ref="formRef" label-width="100px">
        <FormGroup v-model="formData" :json="formJson">
          <template #pwTips>
            <div
              style="color: red; padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding)"
            >
              排为【从南往北】数，户为【从东往西】数
            </div>
            <!-- <van-field v-model="a">  </van-field> -->
          </template>
        </FormGroup>
        <div class="footer">
          <van-button block type="primary" @click="onSubmit"> 提交 </van-button>
        </div>
      </van-form>
    </div>

    <!-- 乡镇地址选择 -->
    <!-- <Cascader v-model:show="showAddress" v-model:desc="formData._address" :options="district" /> -->
    <Address v-model:show="showAddress" v-model:desc="formData._address" />
    <!-- 籍贯选择 -->
    <!-- <Cascader v-model:show="showNativePlace" v-model:desc="formData.hjaddress" :options="town" /> -->
    <Address v-model:show="showNativePlace" v-model:desc="formData.hjaddress" type="native_place" />

    <!-- 学校地址 -->
    <!-- <Cascader v-model:show="showSchool" v-model:desc="formData._schoolAddress" :options="school" /> -->
    <School v-model:show="showSchool" v-model:desc="formData._schoolAddress" />

    <!-- 教职工学习地址 -->
    <!-- <Cascader v-model:show="showTeachSchool" v-model:desc="formData.jzgdwname" :options="school" /> -->
    <School v-model:show="showTeachSchool" v-model:desc="formData.jzgdwname" />

    <!-- 单位 -->
    <!-- <Cascader v-model:show="showCompany" v-model:desc="formData.dwname" :options="company" /> -->
    <Company v-model:show="showCompany" v-model:desc="formData.dwname" />

    <div class="success" v-if="showSuccess">
      <div class="icon"><img src="@/assets/icon-success.png" alt="" /></div>
      <div class="text">提交成功</div>
      <div class="info">
        <div class="info-item">
          <div class="info-label">姓名</div>
          <div class="info-value">{{ formatName(formData.username) }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">身份证号</div>
          <div class="info-value">{{ idCard(formData.cardno) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { Notify, Toast, Dialog } from 'vant'
import { useRoute } from 'vue-router'

import http from '@/utils/http'
import formRule from '@/utils/form-rule'

import FormGroup from '@/components/FormGroup.vue'
import Cascader from '@/components/Cascader.vue'
import Address from '@/components/Address.vue'
import School from '@/components/School.vue'
import Company from '@/components/Company.vue'

// import { district, town } from '@/data/district'
// import company from '@/data/company.json'
// import school from '@/data/school.json'
import nation from '@/data/nation'

const { query } = useRoute()

const required = true
const whether = {
  type: 'radio',
  options: [
    { label: '是', value: '是' },
    { label: '否', value: '否' },
  ],
}

const showSuccess = ref(false)
const showAddress = ref(false)
const showSchool = ref(false)
const showTeachSchool = ref(false)
const showNativePlace = ref(false)
const showCompany = ref(false)

const formRef = ref()
const formData = reactive({
  sfbdhj: '是',

  // sfbdhj: '是',
  // hjno: '12313',
  // username: '法外张三',
  // sex: 2,
  // nation: '汉族',
  // cardType: 2,
  // cardno: '141182199203240102',
  // hjaddress: '淮阳区/临蔡镇',
  // yhzgx: '户主',
  // tel: '13880582267',
  // sfbrsjh: '否',
  // sfzh: '租房',
  // _address: '淮阳区/临蔡镇/常庄行政村/范庄',
  // sfzhy: '否',
  // outaddress: '北京市/北京市/东城区',
  // zytype: '本地在校生',
  // _schoolAddress: '鲁台镇/花庄小学',
  // sfzx: '否',
  // xytxhz: '否',
  // jcbhz: '否',
  // area: '淮阳区',
  // areajd: '临蔡镇',
  // areajwh: '常庄行政村',
  // xqmc: '范庄',
  // schooladdress: '鲁台镇/花庄小学',
  // schoolname: '花庄小学',
  // jtrs: '5',
})

const localJson = computed(() => {
  if (formData['sfbdhj'] != '是') return []

  return [
    { name: 'hjno', label: '户口本户籍编号', rules: formRule.number },

    ...baseInfo.value,

    {
      name: 'hjaddress',
      label: '户口所在地',
      required,
      isLink: true,
      readonly: true,
      on: {
        click() {
          showNativePlace.value = true
        },
      },
    },

    {
      name: 'yhzgx',
      label: '与户主关系',
      required,
      type: 'select',
      options: [
        { label: '户主', value: '户主' },
        { label: '配偶', value: '配偶' },
        { label: '之子', value: '之子' },
        { label: '之女', value: '之女' },
        { label: '之孙子', value: '之孙子' },
        { label: '之孙女', value: '之孙女' },
        { label: '之外甥', value: '之外甥' },
        { label: '之外甥女', value: '之外甥女' },
        { label: '之外孙子', value: '之外孙子' },
        { label: '之外孙女', value: '之外孙女' },
        { label: '之儿媳', value: '之儿媳' },
        { label: '之女婿', value: '之女婿' },
        { label: '之父', value: '之父' },
        { label: '之母', value: '之母' },
        { label: '之公公', value: '之公公' },
        { label: '之婆婆', value: '之婆婆' },
        { label: '之岳父', value: '之岳父' },
        { label: '之岳母', value: '之岳母' },
        { label: '之祖父', value: '之祖父' },
        { label: '之祖母', value: '之祖母' },
        { label: '之外祖父', value: '之外祖父' },
        { label: '之外祖母', value: '之外祖母' },
        { label: '之曾孙', value: '之曾孙' },
        { label: '之曾孙女', value: '之曾孙女' },
        { label: '之兄弟', value: '之兄弟' },
        { label: '之兄妹', value: '之兄妹' },
        { label: '之姐弟', value: '之姐弟' },
        { label: '之姐妹', value: '之姐妹' },
        { label: '之侄子', value: '之侄子' },
        { label: '之侄女', value: '之侄女' },
        { label: '其他', value: '其他' },
      ],
    },

    ...(() => {
      const json = []

      if (formData.yhzgx == '户主') {
        json.push({ name: 'jtrs', label: '家庭人数', required, rules: formRule.number, maxlength: 3 })
      }

      return json
    })(),

    {
      name: 'sfzh',
      label: '房屋类型',
      required,
      type: 'radio',
      options: [
        { label: '自有房屋', value: '自有房屋' },
        { label: '租房', value: '租房' },
      ],
    },

    {
      name: '_address',
      label: '在淮居住地址',
      required,
      isLink: true,
      readonly: true,
      on: {
        click() {
          showAddress.value = true
        },
      },
    },
    ...(() => {
      let json = []

      if (formData._address) {
        const last = formData._address.split('/').pop()

        if (last == '排屋') {
          json = json.concat([
            { name: 'pwTips' },
            { name: 'pws', label: '排数', required, rules: [formRule.number] },
            { name: 'pwh', label: '户数', required, rules: [formRule.number] },
          ])
        } else if (last == '单元楼' || formData._address.indexOf('开发区管委会') != -1) {
          json = json.concat([
            { name: 'ldh', label: '单元楼数', required, rules: [formRule.number] },
            { name: 'dyh', label: '单元号', required, rules: [formRule.number] },
            { name: 'lch', label: '层号', required, rules: [formRule.number] },
            { name: 'fjh', label: '室号', required, rules: [formRule.number] },
          ])
        }
      }

      return json
    })(),

    // { name: 'sfxq', label: '是否为小区', required, ...whether },

    // ...(formData.sfxq == '是'
    //   ? [
    //       // { name: 'xqmc', label: '小区名称', required },
    //       { name: 'ldh', label: '楼栋号', required },
    //       { name: 'dyh', label: '单元号', required },
    //       { name: 'lch', label: '层号', required },
    //       { name: 'fjh', label: '室号', required },
    //       // { name: 'xxaddress', label: '现居住详细住址', placeholder: 'XXX小区XX号X单元', required },
    //     ]
    //   : []),

    { name: 'sfzhy', label: '目前是否在淮阳', required, ...whether },

    ...(() => {
      const json = []

      if (formData.sfzhy == '否') {
        json.push({
          name: 'countrytype',
          label: '所在国家',
          required,
          type: 'radio',
          options: [
            { label: '国内', value: '国内' },
            { label: '国外', value: '国外' },
          ],
        })

        if (formData.countrytype == '国内') {
          json.push({
            name: 'outaddress',
            label: '当前地址',
            required,
            type: 'area',
          })
        } else if (formData.countrytype == '国外') {
          json.push({
            name: 'country',
            label: '国外地址',
            required,
          })
        }
      }

      return json
    })(),
  ]
})

const baseInfo = computed(() => {
  const json = [
    { name: 'username', label: '姓名', required, rules: formRule.zh },
    {
      name: 'sex',
      label: '性别',
      required,
      type: 'radio',
      options: [
        { label: '男', value: 1 },
        { label: '女', value: 2 },
      ],
    },
    { name: 'nation', label: '民族', required, type: 'select', options: nation },
    { name: 'tel', label: '手机号', required, rules: formRule.telRules },
    { name: 'sfbrsjh', label: '是否本人手机号', required, ...whether },
  ]

  if (formData.sfbdhj == '否') {
    json.push({
      name: 'cardType',
      label: '证件类型',
      required,
      type: 'radio',
      options: [
        { label: '身份证', value: 1 },
        { label: '其他', value: 2 },
      ],
    })

    if (formData.cardType == 1) {
      json.push({ name: 'cardno', label: '身份证号', required, rules: formRule.cardNoRules, maxlength: 18 })
    } else if (formData.cardType == 2) {
      json.push({ name: 'cardno', label: '证件号码', required })
    }
  } else {
    json.push({ name: 'cardno', label: '身份证号', required, rules: formRule.cardNoRules })
  }

  return json
})

// 本地户籍
const nonLocal = computed(() => {
  if (formData['sfbdhj'] != '否') return []

  return [
    ...baseInfo.value,

    { name: 'hjaddress', label: '户口所在地', required, type: 'area' }, // 户籍地址更改为籍贯

    {
      name: 'sfzh',
      label: '房屋类型',
      required,
      type: 'radio',
      options: [
        { label: '自有房屋', value: '自有房屋' },
        { label: '租房', value: '租房' },
      ],
    },

    {
      name: '_address',
      label: '在淮居住地址',
      required,
      isLink: true,
      readonly: true,
      on: {
        click() {
          showAddress.value = true
        },
      },
    },
    ...(() => {
      let json = []

      if (formData._address) {
        const last = formData._address.split('/').pop()

        if (last == '排屋') {
          json = json.concat([
            { name: 'pwTips' },
            { name: 'pws', label: '排数', required, rules: [formRule.number] },
            { name: 'pwh', label: '户数', required, rules: [formRule.number] },
          ])
        } else if (last == '单元楼' || formData._address.indexOf('开发区管委会') != -1) {
          json = json.concat([
            { name: 'ldh', label: '单元楼数', required, rules: [formRule.number] },
            { name: 'dyh', label: '单元号', required, rules: [formRule.number] },
            { name: 'lch', label: '层号', required, rules: [formRule.number] },
            { name: 'fjh', label: '室号', required, rules: [formRule.number] },
          ])
        }
      }

      return json
    })(),
  ]
})

// 关爱人群JSON
const garqJson = computed(() => {
  // if (formData.sfgarq == '否') return [] // 不是关爱人群

  const allJson = {
    独居老人: { name: 'djlr', label: '是否为独居老人', required, ...whether },
    精神智障: { name: 'jszz', label: '是否为精神智障', required, ...whether },
    长期卧床: { name: 'cqwc', label: '是否为长期卧床', required, ...whether },
    孕妇: { name: 'yf', label: '是否为孕妇', required, ...whether },
    基础病患者: { name: 'jcbhz', label: '是否为基础病患者', required, ...whether },
    血液透析患者: { name: 'xytxhz', label: '是否为血液透析患者', required, ...whether },
  }

  // 每个职业对应选项不同
  const jobOptions = {
    本地在校生: ['基础病患者', '血液透析患者'],
    外地在校生: ['孕妇', '基础病患者', '血液透析患者'],
    本地教职工: ['孕妇', '基础病患者', '血液透析患者'],
    ['机关/事业单位']: ['孕妇', '基础病患者', '血液透析患者'],
    企业单位: ['孕妇', '基础病患者', '血液透析患者'],
    ['个体经商']: ['孕妇', '基础病患者', '血液透析患者'],
    自由职业: ['独居老人', '精神智障', '长期卧床', '孕妇', '基础病患者', '血液透析患者'],
    无业: ['独居老人', '精神智障', '长期卧床', '孕妇', '基础病患者', '血液透析患者'],
    务农: ['独居老人', '精神智障', '孕妇', '基础病患者', '血液透析患者'],
    军人: ['独居老人', '精神智障', '长期卧床', '孕妇', '基础病患者', '血液透析患者'],
    其他: ['独居老人', '精神智障', '长期卧床', '孕妇', '基础病患者', '血液透析患者'],
  }

  const json = []
  if (formData.zytype) {
    jobOptions[formData.zytype].map(key => {
      if (key == '孕妇' && formData.sex != 2) return // 男性不能选是否孕妇

      json.push(allJson[key])
    })
  }

  return json
})

const formJson = computed(() => {
  let base = [
    {
      name: 'sfbdhj',
      label: '户籍类型',
      required,
      type: 'radio',
      options: [
        { label: '淮阳籍', value: '是' },
        { label: '非淮阳籍', value: '否' },
      ],
    },

    ...localJson.value,
    ...nonLocal.value,

    {
      name: 'zytype',
      label: '职业属性',
      required,
      type: 'select',
      options: [
        { label: '本地在校生', value: '本地在校生' },
        { label: '机关/事业单位', value: '机关/事业单位' },
        { label: '本地教职工', value: '本地教职工' },
        { label: '外地在校生', value: '外地在校生' },
        { label: '企业单位', value: '企业单位' },
        { label: '个体经商', value: '个体经商' },
        { label: '自由职业', value: '自由职业' },
        { label: '无业', value: '无业' },
        { label: '务农', value: '务农' },
        { label: '军人', value: '军人' },
        { label: '其他', value: '其他' },
      ],
    },
  ]

  if (formData.zytype == '本地在校生') {
    base = base.concat([
      {
        name: '_schoolAddress',
        label: '学校地址',
        required,
        isLink: true,
        readonly: true,
        on: {
          click() {
            showSchool.value = true
          },
        },
      },
      {
        name: 'sfzx',
        label: '是否住校',
        required,
        ...whether,
      },
    ])
  } else if (formData.zytype == '本地教职工') {
    base.push({
      name: 'jzgdwname',
      label: '学校地址',
      required,
      isLink: true,
      readonly: true,
      on: {
        click() {
          showTeachSchool.value = true
        },
      },
    })
  } else if (formData.zytype == '外地在校生') {
    base.push({
      name: 'schooldomestic',
      label: '学校所在地',
      required,
      type: 'radio',
      options: [
        { label: '国内', value: '国内' },
        { label: '国外', value: '国外' },
      ],
    })

    if (formData.schooldomestic == '国内') {
      base = base.concat([
        {
          name: 'schoolcity',
          label: '学校所在城市',
          required,
          type: 'area',
        },
        {
          name: 'schoolname',
          label: '学校名称',
          required,
        },
      ])
    } else if (formData.schooldomestic == '国外') {
      base = base.concat([
        {
          name: 'schoolcountry',
          label: '学校所在国家',
          required,
        },
        {
          name: 'schoolname',
          label: '学校名称',
          required,
        },
      ])
    }
  } else if (formData.zytype == '企业单位') {
    base.push({
      name: 'qydwname',
      label: '企业名称',
      required,
    })
  } else if (formData.zytype == '机关/事业单位') {
    if (formData.sfbdhj == '是') {
      base.push({
        name: 'dwlocation',
        label: '单位所在地',
        type: 'radio',
        required,
        options: [
          { label: '本地', value: '本地' },
          { label: '外地', value: '外地' },
        ],
      })

      if (formData.dwlocation == '本地') {
        base.push({
          name: 'dwname',
          label: '机关/事业单位名称',
          required,
          isLink: true,
          readonly: true,
          on: {
            click() {
              showCompany.value = true
            },
          },
        })
      } else if (formData.dwlocation == '外地') {
        base.push({
          name: 'dwname',
          label: '机关/事业单位名称',
        })
      }
    } else if (formData.sfbdhj == '否') {
      base.push({
        name: 'dwname',
        label: '机关/事业单位名称',
        required,
        isLink: true,
        readonly: true,
        on: {
          click() {
            showCompany.value = true
          },
        },
      })
    }
  }

  return [...base, ...garqJson.value]
})

const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const submit = () => {
        const addressParse = formData._address.split('/')

        if (formData._address.indexOf('开发区管委会') != -1) {
          body.areajd = addressParse[1]
          body.areajwh = ''
          body.xqmc = addressParse[2]
        } else {
          body.areajd = addressParse[1] // 街道/乡镇
          body.areajwh = addressParse[2] // 现住居委会/村委会
          body.xqmc = addressParse[3] // 小区/自然村
        }

        if (body.zytype == '本地在校生' && body._schoolAddress) {
          body.schooladdress = body._schoolAddress
          // const schoolAddressParse = formData._schoolAddress.split('/')
          // body.schooladdress = schoolAddressParse[0]
          // body.schoolname = schoolAddressParse[1]
        }

        if (body.zytype == '本地教职工' && body._schoolAddress) {
          body.schooladdress = body._schoolAddress
        }

        // 本地户籍，身份证类型必须是身份证
        if (formData.sfbdhj == '是') body.cardType = 1

        http({
          method: 'post',
          url: '/person_info/collect',
          loading: '提交中...',
          data: body,
        }).then(res => {
          showSuccess.value = true
          // Toast({
          //   type: 'success',
          //   duration: 0,
          //   message: '提交成功',
          //   overlay: true,
          // })
        })
      }

      http({
        url: '/person_info/checkCardno',
        params: {
          cardno: formData.cardno,
        },
      }).then(res => {
        if (res) {
          Dialog.confirm({
            title: '提示',
            message: '当前身份证号已登记，是否确认提交？ 提交将覆盖原有记录！',
          }).then(() => {
            submit()
          })
        } else {
          submit()
        }
      })

      const body = {
        ...formData,
        area: '淮阳区',
      }
    })
    .catch(e => {
      Notify({
        type: 'warning',
        message: '信息未填完整',
      })
    })
}

const formatName = name => {
  if (!name) name = ''

  var newStr
  if (name.length === 2) {
    newStr = name.substr(0, 1) + '*'
  } else if (name.length > 2) {
    var char = ''
    for (let i = 0, len = name.length - 2; i < len; i++) {
      char += '*'
    }
    newStr = name.substr(0, 1) + char + name.substr(-1, 1)
  } else {
    newStr = name
  }
  return newStr
}

const idCard = data => {
  if (!data) data = ''
  return data.replace(/(.{6}).*(.{4})/, '$1********$2')
}
</script>
<style lang="scss" scoped>
.page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 60px;
}

.footer {
  position: fixed;
  background-color: #fff;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 5px 10px;
}

.success {
  position: fixed;
  background-color: #fff;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding-top: 70px;

  .icon {
    text-align: center;
    img {
      width: 130px;
    }
  }

  .text {
    font-size: 18px;
    color: #000;
    text-align: center;
  }

  .info {
    background-color: #fafafa;
    border-radius: 4px;
    margin: 0 auto;
    width: 80%;
    margin-top: 30px;
    padding: 12px;
    .info-item {
      display: flex;
      line-height: 30px;
      .info-label {
        flex: 1;
        color: #999;
      }
    }
  }
}
</style>
